package com.easy.dfc.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easy.core.web.BaseController;
import com.easy.dfc.Utils.*;
import com.easy.dfc.Utils.Error;
import com.easy.dfc.entity.*;
import com.easy.dfc.service.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/17.
 */
@Controller
@RequestMapping("${apiPath}/product")
public class ProductController extends BaseController {

    @Resource
    private FactorySetService factorySetService;

    @Resource
    private ProductsetService productsetService;

    @Resource
    private UsersetService usersetService;

    @Resource
    private TiantiantejiaService tiantiantejiaService;

    @Resource
    private TiaoweihuosetService tiaoweihuosetService;

    @Resource
    private TuangouService tuangouService;

    @Resource
    private ImgSetService imgSetService;

    @Resource
    private SkuSetService skuSetService;

    /**
     * 上传产品
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/ProductAdd", method = RequestMethod.POST)
    @Transactional
    public ResponseEntity<JSONObject> ProductAdd(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            ProductsetWithBLOBs productsetWithBLOBs = new ProductsetWithBLOBs();
            productsetWithBLOBs.setDetail(request.getParameter("Detail"));
            String productId = UUID.randomUUID().toString();
            productsetWithBLOBs.setProductid(productId);
            productsetWithBLOBs.setIsenabled(1);
            productsetWithBLOBs.setMainimg(request.getParameter("MainImg"));
            productsetWithBLOBs.setMainVideoId(Util.getRequestString(request.getParameter("MainVideoId")));
            productsetWithBLOBs.setBrandId(Integer.parseInt(request.getParameter("BrandId")));
            productsetWithBLOBs.setName(request.getParameter("Name"));
            productsetWithBLOBs.setItemno(request.getParameter("ItemNo"));
            productsetWithBLOBs.setTagId(Integer.parseInt(request.getParameter("CategoryTagId")));
            productsetWithBLOBs.setPrice(new BigDecimal(request.getParameter("Price")));
            productsetWithBLOBs.setDetailVideoId(Util.getRequestString(request.getParameter("DetailVideoId")));
            productsetWithBLOBs.setUnit("件");
            if (Util.getRequestString(request.getParameter("DeliveryTime")) != null) {
                productsetWithBLOBs.setDeliveryTime(Integer.parseInt(request.getParameter("DeliveryTime")));//发货时间
            }
            if (Util.getRequestString(request.getParameter("ApproTime")) != null) {
                productsetWithBLOBs.setApproTime(Integer.parseInt(request.getParameter("ApproTime")));//包换时间
            }
            productsetWithBLOBs.setSellerGuarantee(Integer.parseInt(request.getParameter("SellerGuarantee")));//买家保障，0：无，1：有
            productsetWithBLOBs.setSupportArrears(Integer.parseInt(request.getParameter("SupportArrears")));//是否支持欠款，0：否，1：是
            UnitConversionSet unitConversionSet = new UnitConversionSet();
            unitConversionSet.setFrom("手");
            unitConversionSet.setTo("件");

            unitConversionSet.setNum(Integer.parseInt(request.getParameter("UnitConversionNum")));
            ProductProperties productProperties = new ProductProperties();
            productProperties.setInnerpercent(Util.getRequestString(request.getParameter("InnerPercent")));
            productProperties.setSafelevel(Integer.parseInt(request.getParameter("SafeLevel")));
            productProperties.setMaterials(request.getParameter("Materials"));
            productProperties.setMaterialspercent(request.getParameter("MaterialsPercent"));
            productProperties.setSeason(request.getParameter("Season"));
            productProperties.setThick(request.getParameter("Thick"));
            productProperties.setMinsize(Integer.parseInt(request.getParameter("MinSize")));
            productProperties.setMaxsize(Integer.parseInt(request.getParameter("MaxSize")));
            productProperties.setSex(request.getParameter("Sex"));
            List<SkuSet> skuSets = new ArrayList<>();
            String Skulist = request.getParameter("SkuList");
            JSONArray jsonArray = JSONObject.parseArray(Skulist);
            for (Object object : jsonArray) {
                JSONObject json = JSONObject.parseObject(object.toString());
                SkuSet skuSet = new SkuSet();
                skuSet.setIndex(json.getInteger("Index"));
                skuSet.setName(json.getString("Name"));
                skuSet.setStock(json.getInteger("Stock"));
                skuSets.add(skuSet);
            }
            List<ImgSet> imgSets = new ArrayList<>();
            String ImgList = request.getParameter("ImgList");
            jsonArray = JSONObject.parseArray(ImgList);
            for (Object object : jsonArray) {
                JSONObject json = JSONObject.parseObject(object.toString());
                ImgSet imgSet = new ImgSet();
                imgSet.setIndex(json.getInteger("Index"));
                imgSet.setUrl(json.getString("Url"));
                imgSets.add(imgSet);
            }
            List<ProductSize> productSizes = new ArrayList<>();
            String SizeList = request.getParameter("SizeList");
            jsonArray = JSONObject.parseArray(SizeList);
            for (Object object : jsonArray) {
                JSONObject json = JSONObject.parseObject(object.toString());
                ProductSize productSize = new ProductSize();
                productSize.setSize(json.getInteger("Size"));
                productSize.setProductid(productId);
                productSizes.add(productSize);
            }
            //先创建产品，再创建其他信息
            productsetService.insertSelective(productsetWithBLOBs);
            int Id = productsetWithBLOBs.getId();
            productProperties.setProductid(Id);
            productsetService.insertSelective(productProperties);
            for (SkuSet s : skuSets) {
                s.setProductId(Id);
                skuSetService.insertSelective(s);
            }
            for (ImgSet i : imgSets) {
                i.setProductId(Id);
                imgSetService.insertSelective(i);
            }
            for (ProductSize p : productSizes) {
                productsetService.insertSelective(p);
            }
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 上传产品图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/UploadImg", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> UploadImg(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();

                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        String key = new Date().getTime() + file.getOriginalFilename();
                        Util.OSSUpload("productpictures", key, file.getInputStream());
                        //String path = "http://factoryimgs.oss-cn-shanghai.aliyuncs.com/" + key;

                        String path = "http://productpictures.oss-cn-shanghai.aliyuncs.com/" + key;
                        jsonObject.put("Err", Error.OK);
                        jsonObject.put("Url", path);
                    }
                }
            }
        } catch (IOException e) {
            jsonObject.put("Err", Error.UploadFaild);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 产品详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/ProductShow", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> ProductShow(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            String ProductId = Util.ToUuidString(request.getParameter("ProductId").replaceAll("-", ""));
            ProductsetWithBLOBs productsetWithBLOBs = productsetService.selectByProductId(ProductId);
            if (productsetWithBLOBs == null) {
                jsonObject.put("Err", Error.NotProduct);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            //判断是否在活动中
            Util.PromotionStuts(productsetWithBLOBs, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            //获取图片列表
            List<ImgSet> imgSetList = imgSetService.selectByProductId(productsetWithBLOBs.getId());
            //获取Sku列表
            List<SkuSet> skuSetList = skuSetService.selectByProductId(productsetWithBLOBs.getId());
            //获取尺寸列表
            List<ProductSize> productSizes = productsetService.selectProductSizeByProductId(productsetWithBLOBs.getProductid());
            productsetWithBLOBs.setImglist(imgSetList);
            productsetWithBLOBs.setSkuList(skuSetList);
            productsetWithBLOBs.setProductSizes(productSizes);
            String str = JSONObject.toJSONString(productsetWithBLOBs);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 所有产品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/ProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> FactoryList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectProductList(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 所有产品上新列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/NewProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> NewProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectNewProductList(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(com.easy.dfc.Utils.Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 热卖产品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/HotProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> HotProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectHotProductList(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(com.easy.dfc.Utils.Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }
}
